package com.d1711.zhanggm.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.d1711.zhanggm.springboot.entity.Area;
import com.d1711.zhanggm.springboot.entity.AreaVo;
import com.d1711.zhanggm.springboot.mapper.AreaMapper;
import com.d1711.zhanggm.springboot.service.IAreaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张国明
 * @since 2020-05-27
 */
@Service
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area> implements IAreaService {

    @Override
    public List<AreaVo> getListAll() {
        //返回结果
        List<AreaVo> result = new ArrayList<>();
        //查询所有地区数据
        //select id,name,pid from t_area
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select("id","name","pid");
        List<Area> allAreaList = this.list(queryWrapper);
        //查找省的数据
        //select id,name,pid from t_area where pid=1
        allAreaList.forEach(provice->{
            //等于1就是省的数据
            if(provice.getPid()==1){
                AreaVo areaVo = new AreaVo();
                BeanUtils.copyProperties(provice,areaVo);
                result.add(areaVo);
            }
        });
        //查询市的数据
        result.forEach(provice->{
            //查找provice，下市的数据
            List<AreaVo> cityList = new ArrayList<>();
            allAreaList.forEach(city->{
                if(city.getPid().intValue()==provice.getId().intValue()){
                    AreaVo cityVo = new AreaVo();
                    BeanUtils.copyProperties(city,cityVo);
                    cityList.add(cityVo);
                    //查询区的数据
                    List<AreaVo> areaList = new ArrayList<>();
                    allAreaList.forEach(area->{
                        if(area.getPid().intValue()==city.getId().intValue()){
                            AreaVo areaVo = new AreaVo();
                            BeanUtils.copyProperties(area,areaVo);
                            areaList.add(areaVo);
                        }
                    });
                    cityVo.setSubList(areaList);
                }
            });
            provice.setSubList(cityList);
        });
        return result;
    }
}
